package com.bcdat.sso_user_management.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bcdat.sso_user_management.comm.Result;
import com.bcdat.sso_user_management.comm.ResultCode;
import com.bcdat.sso_user_management.exception.BusinessException;
import com.bcdat.sso_user_management.model.User;
import com.bcdat.sso_user_management.service.SimpleHashService;
import com.bcdat.sso_user_management.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * @author zhaolele
 * @date 2019-09-25 11:21
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    SimpleHashService hashService;

    @PostMapping("add")
    public Result addUser(@RequestBody User user) throws BusinessException {
        User existUser = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername()));
        if (existUser != null) {
            throw new BusinessException(ResultCode.DATA_ALREADY_EXISTED);
        }
        String hashPassword = hashService.simpleHash(user.getUsername(), user.getPassword());
        user.setPassword(hashPassword);
        if (!userService.save(user)) {
            throw new BusinessException(ResultCode.DATA_OPERATE_FAILED);
        }
        User newUser = userService.getById(user.getId());
        return Result.success(newUser);
    }

}
